/**
 * 使用方法
 * 1、连接某个 XilujobChat
 */
let XilujobChat = {
    url: "wss://www.example.com:8282",
    instance: undefined,//实例
    userinfo: null,
    receive_user_id:0,
    evts:undefined,
    Timer:null,
    wsBreakLinkNum: 0, // 断开重连次数
    connectSocketTimeOut: null, //终止重新连接
    emoList:[], //表情
    maxRetryCount:10,
    messageCount:0,
    //获取cookie（HttpOnly不为true的）
    getToken:function(name){
        var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null;
        if(cookieStart > -1){
            var cookieEnd = document.cookie.indexOf(";",cookieStart);
            if(cookieEnd == -1){
                cookieEnd = document.cookie.length;
            }
            cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
        }
        return cookieValue;
    },
    open() {
        let token = XilujobChat.getToken('token');
        if(!token){
            return '';
        }
        if (XilujobChat.instance) return;
        XilujobChat.url = XilujobChat.url + '?token='+token;
        XilujobChat.instance = new WebSocket(XilujobChat.url);
        XilujobChat.instance.onopen = XilujobChat.WSOpen;
        XilujobChat.instance.onmessage = XilujobChat.WSMessage;
        XilujobChat.instance.onclose = XilujobChat.WSClose;
        XilujobChat.instance.onerror = XilujobChat.WSClose;
        XilujobChat.eventInit();
    },
    WSOpen (e) {
        //设置心跳
        XilujobChat.Timer = setInterval(XilujobChat.wsSend, 19999); //定时发送心跳
    },

    WSMessage(e) {
        if (!e.data) return
        let msg = JSON.parse(e.data);
        console.log('liixixi', msg)
        if (msg.code == 0) {
            Layer.open({
                //formType: 2,//这里依然指定类型是多行文本框，但是在下面content中也可绑定多行文本框
                title: '提示',
                btnAlign: 'c',
                closeBtn:'1',//右上角的关闭
                content: msg.msg,
                btn:['确认','关闭'],
                yes: function (index, layero) {

                }
            })
            return;
        }
        XilujobChat.handleMsg(msg);
    },
    // 断线重连
    WSClose(e) {
        console.log('关闭');
        if (XilujobChat.Timer != null) {
            clearInterval(XilujobChat.Timer);
        }
        console.log(e)
        if (XilujobChat.maxRetryCount) {
            XilujobChat.Timer = setInterval(XilujobChat.retryWebSocket, 3000); //每3秒重新连接一次
        }
    },
    /**
     * 断线重连
     */
    retryWebSocket: function() {
        if (XilujobChat.wsBreakLinkNum < XilujobChat.maxRetryCount) {
            XilujobChat.wsBreakLinkNum++;
            XilujobChat.open();
            console.log('重连 WebSocket 第' + XilujobChat.wsBreakLinkNum + '次');
        } else {
            if (XilujobChat.Timer != null) {
                clearInterval(XilujobChat.Timer);
            }
            alert('Websocket连接失败');
            // if (app.globalData.chat_config.ReConnection) {
            // 	console.log('每隔10秒将再次尝试重连 WebSocket');
            // 	app.globalData.chat_config.Timer = setInterval(this.connectSocket, 10000); //每10秒重新连接一次
            // }
        }
    },
    WSError(e){
        console.log('wss:onError',e);
    },
    //检查心跳  默认30s ping 一次，检测是否保持连接
    wsSend (message) {
        if (!XilujobChat.instance) return '';
        if(!message){
            XilujobChat.instance.send(`{
            "type": "ping"
      }`)
        }else{
            XilujobChat.instance.send(message);
        }

    },
    /**
     * 推送来的消息处理
     * @param {Object} ret
     */
    handleMsg: function(ret) {
        if(ret.code ==2) {
            return '';
        }
        switch (ret.type) {
            case 'login':
                XilujobChat.emoList = ret.data.chat_memes; // 表情
                XilujobChat.messageCount = ret.data.unread_num;
                XilujobChat.userinfo = ret.data.user_info
                //未读消息
                XilujobChat.getUnreadMessageCount();
                break;
            case 'session_list':
                // 处理会话列表
                XilujobChat.handleSessionList(ret.data.data);
                break;
            case 'del_chat':
                // 删除会话
                app.eventBus.emit('del_chat', ret.data);
                break;
            case 'del_session':
                // 删除会话
                app.eventBus.emit('del_session', data);
                break;
            case 'msg_list':
                // 聊天记录
                var data = this.handleMsgList(ret);
                console.log('msgList',data);
                break;
            case 'new_msg':
                // 好友发消息
                this.newMsg(ret.data);
                this.getUnreadMessageCount()
                break;
            case 'say':
                //我发送的消息，推给我
                this.newMsg(ret.data);
                break;
            case 'set_read':
                break;
            case "message_count":
                // 设置底部菜单的角
                $("#message-bubble i").text(ret.data.unread_num);
                break;
            default:
                break;
        }
    },
    //未读消息
    getUnreadMessageCount(){
        XilujobChat.wsSend(`{
            "type": "getmessagecount"
        }`);
    },
    //聊天用户列表
    getChatUserList(){
        XilujobChat.wsSend(`{
            "type": "sessionlist",
            "page":1,
            "pagesize":50
        }`);
    },
    //聊天内容列表
    getMsgList(receive_user_id, page){
        XilujobChat.wsSend(JSON.stringify({
            "type": 'msglist',
            "page": page,
            "receive_user_id": receive_user_id
        }));
    },
    //聊天记录已读
    setRead(receive_user_id){
        XilujobChat.wsSend(JSON.stringify({
            type: 'setread',
            receive_user_id: receive_user_id
        }));
    },
    //新消息
    newMsg(data) {
        if(!$(".chat-mask,.chat-wrapper").hasClass('hide')){
            XilujobChat.getChatUserList();
        }
        if (data.to_uid != XilujobChat.receive_user_id && data.from_uid != XilujobChat.receive_user_id && !$(".chat-mask,.chat-wrapper").hasClass('hide')) {
            return false;
        }
        var ret = XilujobChat.handle_msg_data(data);
        let html = XilujobChat.onChat(ret.data[0]);
        $(".right .active-chat #chat_scroll").append(html);
        var chat_scroll = document.getElementById("chat_scroll");
        chat_scroll.scrollTop = chat_scroll.scrollHeight;
        if (data.from_uid == XilujobChat.receive_user_id && !$(".chat-mask,.chat-wrapper").hasClass('hide')) {
            XilujobChat.wsSend({
                type: 'setread',
                receive_user_id: XilujobChat.receive_user_id
            });
        }
    },
    //聊天进程列表分页
    handleSessionList(data){
        //获取聊天列表
        var html = '';
        data.forEach(item=>{

            html += '<li class="person '+(XilujobChat.userinfo.user_id == item.receive_user_id?"":"")+'" data-user_id="'+(XilujobChat.userinfo.user_id != item.receive_user_id ? item.receiveuser.id : item.senduser.id)+'" data-username="'+(XilujobChat.userinfo.user_id != item.receive_user_id ? item.receiveuser.nickname : item.senduser.nickname)+'">';
            html += '<img class="person_avatar '+(item.is_online?"person_head_gray":"person_head_gray")+'" src="'+(XilujobChat.userinfo.user_id!=item.receive_user_id?item.receiveuser.avatar:item.senduser.avatar)+'" alt="">';
            html += '<div class="session_info_item"><span class="name">'+(XilujobChat.userinfo.user_id!=item.receive_user_id?item.receiveuser.nickname:item.senduser.nickname )+'</span><span class="time">'+item.newmsg.createtime_text+'</span></div>';
            html += '<div class="session_info_item">';
            let content = '';
            if(item.newmsg.type==6){
                content = "【面试邀请】";
            }else if(item.newmsg.type==4){
                content = "【职位投递】";
            }else if(item.newmsg.type==3){
                content = "【职位咨询】";
            }else if(item.newmsg.type==2){
                content = "【图片】";
            }else if(item.newmsg.type==1){
                content = item.newmsg.message;
            }
            html += '<span class="preview">'+content+'</span>';
            if(item.unread_num>0){
                html +='<span class="unread_msg_count count_hide" style="display: block;">'+item.unread_num+'</span>';
            }else{
                html +='<span class="unread_msg_count count_hide" style="display: none;">0</span>';
            }
            html += '</div>';
            html += '</li>';
        });
        $(".chat-container #session_list").html(html);

    },

    /**
     * 聊天消息列表
     */
    handleMsgList: function(ret) {
        var res = ret.data;
        if (res.total == 0) {
            return {
                data: res,
                receive_user: ret.receiveuser
            };
        }
        var array = [];
        var new_arr = [];
        var min_time = res.data[res.data.length - 1].createtime;
        var min_time_text = res.data[res.data.length - 1].createtime_text;
        array[min_time_text] = [];
        for (let index = res.data.length - 1; index >= 0; index--) {
            const v = res.data[index];
            // 处理表情包
            v.message = v.type == 1 ? XilujobChat.changeEmotion(v.message) : v.message; // 如果当前时间和最早时间相差不超过10分钟，就分为一组

            if (v.createtime - min_time <= 600) {
                array[min_time_text].push(v);
            } else {
                min_time = v.createtime;
                min_time_text = v.createtime_text;
                array[min_time_text] = [];
                array[min_time_text].push(v);
            }
        }
        for (const key in array) {
            new_arr.push({
                time: key,
                data: array[key]
            });
        }
        res.data = new_arr;
        //console.log(res.data);
        // $(".right .active-chat #chat_scroll").html('');
        var html = '';
        res.data.forEach(item=>{
            html += XilujobChat.onChat(item);
        });
        $(".right .active-chat #chat_scroll").html(html);
        var chat_scroll = document.getElementById("chat_scroll");
        chat_scroll.scrollTop = chat_scroll.scrollHeight;

        // return {
        //     data: res,
        //     receive_user: ret.receiveuser
        // };
    },

    //处理一个聊天列表分页-暂时未用到
    handle_msg_data: function(data) {
        var new_arr = [];

        data.message = data.type == 1 ? XilujobChat.changeEmotion(data.message) : data.message;
        new_arr.push({
            time: data.createtime_text,
            data: [data]
        });
        return {
            data: new_arr,
        };
    },

    //表情
    changeEmotion: function(contents) {
        var emotions = XilujobChat.emoList;
        var pattern1 = /\[[\u4e00-\u9fa5]+\]/g;
        var pattern2 = /\[[\u4e00-\u9fa5]+\]/;

        if (contents) {
            contents = contents.replace(new RegExp(/\<br>/, 'g'), '\n');
            contents = contents.replace(new RegExp(/\<br\/>/, 'g'), '\n');
        }

        var content = contents.match(pattern1);
        var str = contents;
        var now_str = contents;
        var arr = [];
        if (content == null)
            return [{
                type: 1,
                value: str
            }];

        for (var i = 0; i < content.length; i++) {
            var src = '';

            for (var j = 0; j < emotions.length; j++) {
                if (emotions[j].name == content[i]) {
                    src = emotions[j].image;
                    break;
                }
            }

            if (!now_str) {
                break;
            }

            var has_i = now_str.indexOf(content[i]);

            if (has_i != -1) {
                arr.push({
                    type: 1,
                    value: now_str.substring(0, Number(has_i))
                });
                arr.push({
                    type: 2,
                    value: src
                });
                now_str = now_str.substring(Number(has_i) + Number(content[i].length));

                if (i == content.length - 1) {
                    arr.push({
                        type: 1,
                        value: now_str
                    });
                }
            }
        }

        return arr;
    },
    // 接受本地消息
    onChat(msg) {
        var html = '<div class="conversation-start"><span>'+msg.time+'</span></div>';

        for (let i=0;i<msg.data.length;i++){
            html += '<div class="bubble '+(msg.data[i].from_uid==XilujobChat.receive_user_id?'you':'me')+'">';
            if(msg.data[i].type == 6){
                //面试邀请
                html += '<div class="job_card"><div class="card_body"><div class="job_name">'+msg.data[i].message_text.name+'</div><div class="job_salary">'+msg.data[i].message_text.salary+'</div><div class="job_label m-list-flex">';
                html += '<div class="label">'+msg.data[i].message_text.city+'</div> - <div class="label">'+msg.data[i].message_text.district+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.education_level+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.work_experience+'</div>';
                msg.data[i].message_text.benefits.forEach(item=>{
                    html += '<div class="label">' + item.name + '</div>';
                })
                html +='</div></div><div class="card_foot m-list-flex"><img class="icon_company" src="'+msg.data[i].message_text.company_logo+'" /><div class="m-cell-bd">'+msg.data[i].message_text.company_name+'</div></div>';
                html += '<div class="interview_box"><div class="title1 mb10">面试信息</div><div class="m-list-flex mb10">\n' +
                    '<div class="title2">面试时间</div><div class="m-cell-bd val">'+msg.data[i].message_text.interview_time+'</div></div><div class="m-list-flex"><div class="title2">面试地址</div><div class="m-cell-bd val">'+msg.data[i].message_text.interview_address+'</div></div>';
                html += '<div class="btn_wrap m-list-flex">';
                if((!msg.data[i].message_text.status || msg.data[i].message_text.status==0) && msg.data[i].from_uid!=XilujobChat.userinfo.user_id){
                    html += '<div class="zbtn1">拒绝面试</div><div class="zbtn2">同意面试</div>';
                }
                html += '</div>'
                if(msg.data[i].message_text.status == 1){
                    html += '<div class="btn_wrap m-list-flex"><div class="zbtn1">已拒绝</div></div>';
                }else if(msg.data[i].message_text.status == 2){
                    html += '<div class="btn_wrap m-list-flex"><div class="zbtn2">已同意</div></div>';
                }
                html += '</div></div>';
            }else if(msg.data[i].type == 5){
                //空白
            }else if(msg.data[i].type == 4){
                //投递
                html += '<div class="job_card"><div class="card_body"><div class="job_name">'+msg.data[i].message_text.name+'</div><div class="job_salary">'+msg.data[i].message_text.salary+'</div><div class="job_label m-list-flex">';

                html += '<div class="label">'+msg.data[i].message_text.city+'</div> - <div class="label">'+msg.data[i].message_text.district+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.education_level+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.work_experience+'</div>';
                msg.data[i].message_text.benefits.forEach(item=>{
                    html += '<div class="label">' + item.name + '</div>';
                })
                html += '</div></div><div class="card_foot m-list-flex"><div class="m-cell-bd">投递成功</div></div></div>';
            }else if(msg.data[i].type == 3){
                //职位
                html += '<div class="job_card"><div class="card_body"><div class="job_name">'+msg.data[i].message_text.name+'</div><div class="job_salary">'+msg.data[i].message_text.salary+'</div><div class="job_label m-list-flex">';

                html += '<div class="label">'+msg.data[i].message_text.city+'</div> - <div class="label">'+msg.data[i].message_text.district+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.education_level+'</div>';
                html += '<div class="label">'+msg.data[i].message_text.work_experience+'</div>';
                msg.data[i].message_text.benefits.forEach(item=>{
                    html += '<div class="label">' + item.name + '</div>';
                })
                html += '</div></div></div>';
            }else if(msg.data[i].type == 2){
                //图片
                html += '<img width="80px" title="" src="'+msg.data[i].message+'">'
            }else if(msg.data[i].type == 1){
                //文本
                msg.data[i].message.forEach(item=>{
                    if(item.type ==1){
                        html += item.value;
                    }else{
                        html += '<img width="40px" title="" src="'+item.value+'">'
                    }
                })
            }
            html+='</div>';
        }
        return html;
    },
    eventInit(){
        //点击消息按钮
        $(document).on('click','li#message-bubble',function () {
            $(".chat-mask,.chat-wrapper").removeClass('hide');
            XilujobChat.getChatUserList();
            return false;
        })
        //关闭聊天弹窗
        $(document).on('click','div.chat-mask',function () {
            $(".chat-mask,.chat-wrapper").addClass('hide');
        })
        //点击单个用户及聊天内容
        $(document).on('click','li.person',function () {
            var userId = $(this).data('user_id');
            var nickname = $(this).find('.name').text();
            $(".right #session_user_name").text(nickname);
            $(this).addClass('active').siblings().removeClass('active');
            XilujobChat.receive_user_id = userId;
            XilujobChat.getMsgList(userId,1);
            XilujobChat.setRead(userId);
            XilujobChat.getUnreadMessageCount();
            $(this).find(".unread_msg_count").hide();
        });
        //聊天表情渲染
        $(document).on('click','.smiley',function (e) {
            if(!XilujobChat.receive_user_id){
                return false;
            }
            var html = '';
            XilujobChat.emoList.forEach(item=>{
                html += '<img class="emoji" data-type="'+item.name+'" title="'+item.name+'" src="'+item.image+'">'
            })
            $("#chat_emoji_list").html(html);
            $(".chat_emoji").show();
            return false;
        });
        $(document).on('click','.chat-wrapper,.chat-mask',function () {
            $(".chat_emoji").hide();
        });
        // 聊天框点击事件
        $(document).on('click',"#message",function() {
            // 获取选定对象
            var selection = getSelection();
            // 设置最后光标对象
            XilujobChat.lastTextAreaRange = selection.getRangeAt(0);
        })
        // 聊天框按键弹起事件
        $(document).on('keyup',"#message" , function() {
            // 获取选定对象
            var selection = getSelection();
            // 设置最后光标对象
            XilujobChat.lastTextAreaRange = selection.getRangeAt(0)
        })
        //点击表情
        $(document).on('click','#chat_emoji_list .emoji',function () {
            var text = $(this).data('type');
            var textarea = $("#message");
            textarea[0].focus();
            // 获取选定对象
            var selection = getSelection()
            // 判断是否有最后光标对象存在
            if (XilujobChat.lastTextAreaRange) {
                // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
                selection.removeAllRanges()
                selection.addRange(XilujobChat.lastTextAreaRange)
            }
            // 判断选定对象范围是编辑框还是文本节点
            if (selection.anchorNode.nodeName != '#text') {
                // 如果是编辑框范围。则创建表情文本节点进行插入
                var emojiText = document.createTextNode(text)

                if (textarea[0].childNodes.length > 0) {
                    // 如果文本框的子元素大于0，则表示有其他元素，则按照位置插入表情节点
                    for (var i = 0; i < textarea[0].childNodes.length; i++) {
                        if (i == selection.anchorOffset) {
                            textarea[0].insertBefore(emojiText, textarea[0].childNodes[i])
                        }
                    }
                } else {
                    // 否则直接插入一个表情元素
                    textarea[0].appendChild(emojiText)
                }
                // 创建新的光标对象
                var range = document.createRange()
                // 光标对象的范围界定为新建的表情节点
                range.selectNodeContents(emojiText)
                // 光标位置定位在表情节点的最大长度
                console.log(emojiText.length)
                range.setStart(emojiText, emojiText.length)
                // 使光标开始和光标结束重叠
                range.collapse(true)
                // 清除选定对象的所有光标对象
                selection.removeAllRanges()
                // 插入新的光标对象
                selection.addRange(range)
            }
            else {
                // 如果是文本节点则先获取光标对象
                var range = selection.getRangeAt(0)
                // 获取光标对象的范围界定对象，一般就是textNode对象
                var textNode = range.startContainer;
                // 获取光标位置
                var rangeStartOffset = range.startOffset;
                // 文本节点在光标位置处插入新的表情内容
                textNode.insertData(rangeStartOffset, text)
                // 光标移动到到原来的位置加上新内容的长度
                range.setStart(textNode, rangeStartOffset + text.length)
                // 光标开始和光标结束重叠
                range.collapse(true)
                // 清除选定对象的所有光标对象
                selection.removeAllRanges()
                // 插入新的光标对象
                selection.addRange(range)
            }
            // 无论如何都要记录最后光标对象
            XilujobChat.lastTextAreaRange = selection.getRangeAt(0)
        });

        //图片上传初始化
        require(['upload'],function (Upload) {
            Upload.api.upload($('.select_file #chatfile'),function (data) {
                XilujobChat.wsSend(JSON.stringify({
                    type: 'say',
                    receive_user_id: XilujobChat.receive_user_id,
                    content: Fast.api.cdnurl(data.url),
                    chat_type: 2 //类型:1=文字,2=图片,3=商品
                }));
            });
        })

        //发送
        $(document).on('click','.xilujobchat_footer .send',function () {
            var text = $("#message").text();
            if(!text){
                Toastr.error('聊天内容不得为空');
                return false;
            }
            XilujobChat.wsSend(JSON.stringify({
                type: 'say',
                receive_user_id: XilujobChat.receive_user_id,
                content: text,
                chat_type: 1 //类型:1=文字,2=图片,3=商品
            }));
            $("#message").text("");
            return false;
        })

    }
}
